
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
// import qs from 'qs';

let ROOT = '';
if (process.env.NODE_ENV === 'production') {
  ROOT = process.env.VUE_APP_ROOT;
} else {
  ROOT = '';
}
Vue.use(VueAxios, axios);

// 将全局的根地址绑定到axios的默认基础路径
Vue.axios.defaults.baseURL = ROOT;

// 设置公共请求header信息
Vue.axios.defaults.headers = {
  'Content-Type': 'application/json;charset=UTF-8'
};

/**
 * sendPost请求
 * @param url
 * @param params 参数默认为空对象
 * @returns {Promise}
 */
export function sendPost(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }).catch(err => {
        reject(err);
      });
  });
}

/**
 * sendGet请求
 * @param url
 * @param params 参数默认为空对象
 * @returns {Promise}
 */
export function sendGet(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, data)
      .then(response => {
        resolve(response.data);
      }).catch(err => {
        reject(err);
      });
  });
}

// http request拦截器
Vue.axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    if (config.data instanceof Object) {
      // config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// http response 拦截器
Vue.axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);
export default axios;
